<template>
  <div class="page-container">
    <div class="content-wrapper">
      <!-- 标题区域 -->
      <div class="page-header">
        <div class="title-section">
          <div class="title-indicator"></div>
          <h2>角色管理</h2>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="saveRoles">保存</el-button>
        </div>
      </div>

      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 左侧角色列表 -->
        <div class="left-panel">
          <!-- 角色标题和新增按钮 -->
          <div class="role-header">
            <span class="role-title">角色</span>
            <el-link type="primary" @click="addNewRole" class="add-role-link">+新增角色</el-link>
          </div>

          <div class="role-list">
            <div
              v-for="(role, index) in roles"
              :key="role.id"
              class="role-item"
              :class="{ 'selected': selectedRoleIndex === index }"
            >
              <div class="role-name" @click="selectRole(index)">
                {{ role.name }}
              </div>
              <el-button
                type="danger"
                size="small"
                @click.stop="deleteRole(role.id, index)"
                class="delete-btn"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>

        <!-- 右侧权限管理 -->
        <div class="right-panel">
          <!-- 管理角色权限部分 -->
          <div class="section">
            <div class="section-title">管理角色权限</div>
            <div class="section-content">
              <!-- 全部权限 -->
              <div class="permission-item">
                <el-checkbox
                  v-model="selectAll"
                  :indeterminate="isIndeterminate"
                  @change="handleSelectAll"
                >
                  全部
                </el-checkbox>
              </div>

              <!-- 权限树结构 -->
              <div class="permission-tree">
                <div
                  v-for="(permission, index) in permissionGroups"
                  :key="`permission-${permission.id}`"
                  class="permission-node"
                >
                  <!-- 一级权限 -->
                  <div class="level-1">
                    <el-checkbox
                      v-model="permission.checked"
                      :indeterminate="permission.indeterminate"
                      @change="handleLevelChange(permission)"
                    >
                      {{ permission.pname }}
                    </el-checkbox>
                  </div>

                  <!-- 二级权限 -->
                  <div
                    v-if="permission.children && permission.children.length > 0"
                    class="level-2-container"
                  >
                    <div
                      v-for="child in permission.children"
                      :key="`child-${child.id}`"
                      class="level-2"
                    >
                      <el-checkbox
                        v-model="child.checked"
                        :indeterminate="child.indeterminate"
                        @change="handleLevelChange(child, permission)"
                      >
                        {{ child.pname }}
                      </el-checkbox>

                      <!-- 三级权限（操作权限） -->
                      <div
                        v-if="child.children && child.children.length > 0"
                        class="level-3-container"
                      >
                        <el-checkbox
                          v-for="grandchild in child.children"
                          :key="`grandchild-${grandchild.id}`"
                          v-model="grandchild.checked"
                          @change="handleLevelChange(grandchild, child, permission)"
                          class="level-3"
                        >
                          {{ grandchild.pname }}
                        </el-checkbox>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 新增/编辑角色弹窗 -->
    <el-dialog
      v-model="roleDialogVisible"
      title="编辑角色信息"
      width="600px"
      :before-close="handleCloseDialog"
    >
      <div class="role-form">
        <div class="form-item">
          <label class="form-label">角色名称</label>
          <el-input
            v-model="roleForm.name"
            placeholder="请输入"
            class="form-input"
          />
        </div>

        <div class="form-item">
          <label class="form-label">角色介绍</label>
          <el-input
            v-model="roleForm.description"
            type="textarea"
            placeholder="请输入"
            :rows="6"
            class="form-textarea"
          />
        </div>

        <div class="form-info">
          <div class="info-item">
            <span class="info-label">创建时间</span>
            <span class="info-value">{{ roleForm.createTime }}</span>
          </div>

          <div class="info-item">
            <span class="info-label">创建人</span>
            <span class="info-value">{{ roleForm.creator }}</span>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleSaveRole">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 角色数据
const roles = ref([])

const selectedRoleIndex = ref(0)

// 弹窗控制
const roleDialogVisible = ref(false)

// 角色表单数据
const roleForm = ref({
  name: '',
  description: '',
  createTime: '',
  creator: '王丽心'
})

// 权限组数据
const permissionGroups = ref([])

// 全选状态
const selectAll = ref(false)

// 半选状态
const isIndeterminate = computed(() => {
  if (!permissionGroups.value || permissionGroups.value.length === 0) {
    return false
  }

  const getAllPermissions = (nodes) => {
    let permissions = []
    nodes.forEach(node => {
      if (node && typeof node === 'object') {
        permissions.push(node)
        if (node.children && node.children.length > 0) {
          permissions = permissions.concat(getAllPermissions(node.children))
        }
      }
    })
    return permissions
  }

  const allPermissions = getAllPermissions(permissionGroups.value)
  const checkedCount = allPermissions.filter(p => p && p.checked).length
  return checkedCount > 0 && checkedCount < allPermissions.length
})

// 选择角色
const selectRole = (index) => {
  selectedRoleIndex.value = index
  if (roles.value[index]) {
    loadRolePermissions(roles.value[index].id)
  }
}

// 新增角色
const addNewRole = () => {
  // 重置表单
  roleForm.value = {
    name: '',
    description: '',
    createTime: getCurrentTime(),
    creator: 'admin'  // 默认创建人为admin（id=5）
  }
  roleDialogVisible.value = true
}

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  return `${year}年${month}月${day}日 ${hours}:${minutes}`
}

// 关闭弹窗
const handleCloseDialog = () => {
  roleDialogVisible.value = false
}

// 保存角色
const handleSaveRole = async () => {
  if (!roleForm.value.name.trim()) {
    ElMessage.warning('请输入角色名称')
    return
  }

  try {
    const requestData = {
      name: roleForm.value.name,
      description: roleForm.value.description
    }

    console.log('提交角色数据:', requestData)

    const response = await axios.post('/role/save', requestData)

    console.log('保存角色响应:', response.data)

    if (response.data.success) {
      ElMessage.success('角色保存成功')
      roleDialogVisible.value = false
      loadRoles() // 重新加载角色列表
    } else {
      ElMessage.error(response.data.message || '角色保存失败')
    }
  } catch (error) {
    ElMessage.error('角色保存失败')
    console.error('角色保存失败:', error)
  }
}

// 处理全选
const handleSelectAll = (val) => {
  const setChecked = (node) => {
    if (!node || typeof node !== 'object') return

    node.checked = val
    node.indeterminate = false
    if (node.children && node.children.length > 0) {
      node.children.forEach(setChecked)
    }
  }

  if (permissionGroups.value && Array.isArray(permissionGroups.value)) {
    permissionGroups.value.forEach(setChecked)
  }
}

// 处理层级权限变化
const handleLevelChange = (node, parent = null, grandParent = null) => {
  // 设置子节点状态
  const setChildrenChecked = (node) => {
    node.indeterminate = false
    if (node.children && node.children.length > 0) {
      node.children.forEach(child => {
        child.checked = node.checked
        setChildrenChecked(child)
      })
    }
  }

  setChildrenChecked(node)

  // 更新父节点状态
  if (parent) {
    updateParentStatus(parent)
    if (grandParent) {
      updateParentStatus(grandParent)
    }
  }

  updateSelectAllStatus()
}

// 更新父节点状态
const updateParentStatus = (parent) => {
  if (!parent || !parent.children || parent.children.length === 0) return

  const checkedChildren = parent.children.filter(child => child && child.checked)
  const indeterminateChildren = parent.children.filter(child => child && child.indeterminate)

  if (checkedChildren.length === parent.children.length) {
    parent.checked = true
    parent.indeterminate = false
  } else if (checkedChildren.length === 0 && indeterminateChildren.length === 0) {
    parent.checked = false
    parent.indeterminate = false
  } else {
    parent.checked = false
    parent.indeterminate = true
  }
}

// 更新全选状态
const updateSelectAllStatus = () => {
  if (!permissionGroups.value || permissionGroups.value.length === 0) {
    selectAll.value = false
    return
  }

  const getAllPermissions = (nodes) => {
    let permissions = []
    nodes.forEach(node => {
      if (node && typeof node === 'object') {
        permissions.push(node)
        if (node.children && node.children.length > 0) {
          permissions = permissions.concat(getAllPermissions(node.children))
        }
      }
    })
    return permissions
  }

  const allPermissions = getAllPermissions(permissionGroups.value)
  const checkedCount = allPermissions.filter(p => p && p.checked).length

  if (allPermissions.length > 0 && checkedCount === allPermissions.length) {
    selectAll.value = true
  } else {
    selectAll.value = false
  }
}

// 保存角色权限
const saveRoles = async () => {
  try {
    if (roles.value.length === 0 || selectedRoleIndex.value < 0) {
      ElMessage.warning('请选择一个角色')
      return
    }

    const currentRole = roles.value[selectedRoleIndex.value]
    const selectedPermissionIds = []

    // 递归收集选中的权限ID
    const collectSelectedIds = (nodes) => {
      if (!nodes || !Array.isArray(nodes)) return

      nodes.forEach(node => {
        if (!node || typeof node !== 'object') return

        if (node.checked) {
          selectedPermissionIds.push(node.id)
        }
        if (node.children && node.children.length > 0) {
          collectSelectedIds(node.children)
        }
      })
    }

    collectSelectedIds(permissionGroups.value)

    const response = await axios.put(`/role/${currentRole.id}/permissions`, selectedPermissionIds)

    if (response.data.success) {
      ElMessage.success('保存成功')
    } else {
      ElMessage.error(response.data.message || '保存失败')
    }
  } catch (error) {
    ElMessage.error('保存失败')
    console.error('保存失败:', error)
  }
}

// 加载角色列表
const loadRoles = async () => {
  try {
    const response = await axios.get('/role/list')
    if (response.data.success) {
      roles.value = response.data.data || []
      if (roles.value.length > 0) {
        selectRole(0)
      }
    } else {
      ElMessage.error(response.data.message || '获取角色列表失败')
    }
  } catch (error) {
    ElMessage.error('获取角色列表失败')
    console.error('获取角色列表失败:', error)
  }
}

// 删除角色
const deleteRole = async (roleId, index) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个角色吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await axios.delete(`/role/${roleId}`)

    if (response.data.success) {
      ElMessage.success('删除成功')
      // 重新加载角色列表
      loadRoles()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除角色失败:', error)
    }
  }
}

// 加载权限列表
const loadPermissions = async () => {
  try {
    const response = await axios.get('/role/permissions')
    if (response.data.success) {
      const permissions = response.data.data || []
      // 直接使用树形结构的权限数据
      permissionGroups.value = permissions.map(permission => ({
        ...permission,
        checked: false,
        indeterminate: false,
        children: permission.children ? permission.children.map(child => ({
          ...child,
          checked: false,
          indeterminate: false,
          children: child.children ? child.children.map(grandchild => ({
            ...grandchild,
            checked: false
          })) : []
        })) : []
      }))
    } else {
      ElMessage.error(response.data.message || '获取权限列表失败')
    }
  } catch (error) {
    ElMessage.error('获取权限列表失败')
    console.error('获取权限列表失败:', error)
  }
}

// 加载角色权限
const loadRolePermissions = async (roleId) => {
  try {
    const response = await axios.get(`/role/${roleId}`)
    if (response.data.success) {
      const roleData = response.data.data
      if (roleData && roleData.permissions) {
        const permissionIds = roleData.permissions.map(p => p.id)
        updatePermissionChecked(permissionIds)
      }
    } else {
      ElMessage.error(response.data.message || '获取角色权限失败')
    }
  } catch (error) {
    ElMessage.error('获取角色权限失败')
    console.error('获取角色权限失败:', error)
  }
}

// 更新权限选中状态
const updatePermissionChecked = (permissionIds) => {
  if (!permissionIds || !Array.isArray(permissionIds)) {
    return
  }

  const updateNodeChecked = (node) => {
    if (!node || typeof node !== 'object') return

    node.checked = permissionIds.includes(node.id)
    if (node.children && node.children.length > 0) {
      node.children.forEach(updateNodeChecked)
      updateParentStatus(node)
    }
  }

  permissionGroups.value.forEach(updateNodeChecked)
  updateSelectAllStatus()
}



onMounted(() => {
  loadRoles()
  loadPermissions()
})
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
  display: flex;
  justify-content: center;
}

.content-wrapper {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  width: 1400px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 32px;
  border-bottom: 1px solid #e4e7ed;
}

.title-section {
  display: flex;
  align-items: center;
}

.title-indicator {
  width: 4px;
  height: 22px;
  background: #409EFF;
  border-radius: 2px;
  margin-right: 16px;
}

.title-section h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
  color: #303133;
}

.main-content {
  display: flex;
  min-height: 700px;
}

.left-panel {
  width: 280px;
  border-right: 1px solid #e4e7ed;
  background-color: #f8f9fa;
}

.role-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e4e7ed;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.role-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.add-role-link {
  font-size: 14px;
}

.role-list {
  padding: 0;
}

.role-item {
  padding: 16px 24px;
  color: #606266;
  font-size: 14px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.role-item:hover {
  background-color: #f5f7fa;
}

.role-item.selected {
  background-color: #ecf5ff;
  color: #409EFF;
  position: relative;
}

.role-item.selected::after {
  content: '';
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background: #409EFF;
}

.role-name {
  flex: 1;
  cursor: pointer;
}

.delete-btn {
  opacity: 0;
  transition: opacity 0.3s;
}

.role-item:hover .delete-btn {
  opacity: 1;
}

.right-panel {
  flex: 1;
  padding: 24px 32px;
}

.section {
  margin-bottom: 32px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 16px;
}

.section-content {
  padding-left: 0;
}

.permission-item {
  margin-bottom: 24px;
}

.permission-tree {
  margin-top: 16px;
}

.permission-node {
  margin-bottom: 24px;
}

.level-1 {
  font-weight: 600;
  font-size: 16px;
  margin-bottom: 12px;
}

.level-2-container {
  margin-left: 24px;
}

.level-2 {
  margin-bottom: 12px;
  font-weight: 500;
  font-size: 14px;
}

.level-3-container {
  margin-left: 24px;
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.level-3 {
  font-weight: 400;
  font-size: 14px;
}

.group-permissions .el-checkbox {
  margin-bottom: 8px;
  width: 180px;
}

/* Element Plus 样式覆盖 */
:deep(.el-checkbox__label) {
  font-size: 14px;
  padding-left: 8px;
  color: #606266;
}

:deep(.el-checkbox) {
  margin-right: 0;
  align-items: center;
}

:deep(.el-checkbox__input) {
  margin-right: 0;
}

:deep(.el-link) {
  font-size: 14px;
  text-decoration: none;
}

:deep(.el-button) {
  border-radius: 6px;
  font-size: 14px;
  padding: 10px 20px;
}

:deep(.el-button--primary) {
  background-color: #409EFF;
  border-color: #409EFF;
}

/* 弹窗样式 */
.role-form {
  padding: 20px 0;
}

.form-item {
  margin-bottom: 24px;
  display: flex;
  align-items: flex-start;
}

.form-label {
  width: 80px;
  color: #606266;
  font-size: 14px;
  line-height: 32px;
  margin-right: 16px;
  flex-shrink: 0;
}

.form-input {
  flex: 1;
}

.form-textarea {
  flex: 1;
}

.form-info {
  margin-top: 32px;
  padding-top: 20px;
}

.info-item {
  display: flex;
  margin-bottom: 16px;
}

.info-label {
  width: 80px;
  color: #606266;
  font-size: 14px;
  margin-right: 16px;
  flex-shrink: 0;
}

.info-value {
  color: #303133;
  font-size: 14px;
}

.dialog-footer {
  text-align: right;
}

/* Dialog 样式覆盖 */
:deep(.el-dialog__header) {
  padding: 20px 24px 16px;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 0 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px 20px;
  border-top: 1px solid #e4e7ed;
}

:deep(.el-textarea__inner) {
  resize: none;
}
</style>